<!--
 * @Author: Wushiqi
 * @Descripttion: 设计模式
 * @Date: 2021-05-07 13:45:31
 * @LastEditor: Wushiqi
 * @LastEditTime: 2021-05-07 13:52:04
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>设计模式</title>
</head>
<body>
  <script>
    // 单例模式--不管创建多少个对象都只有一个实例
    var Single = (function () {
      var instance = null
      function Single(name) {
        this.name = name
      }
      return function (name) {
        if (!instance) {
          instance = new Single()
        }
        return instance
      }
    })()

    var oA = new Single('hi')
    var oB = new Single('hello')
    console.log(oA); // Single {name: undefined}
    console.log(oB); // Single {name: undefined}
    console.log(oB === oA); // true

    // 工厂模式--代替new创建一个对象，且这个对象想工厂制作一样，批量制作属性相同的实例对象（指向不同）
    function Animal(o) {
      var instance = new Object()
      instance.name = o.name
      instance.age = o.age
      instance.getAnimal = function () {
        return "name:" + instance.name + " age:" + instance.age
      }
      return instance
    }

    var cat = Animal({name:"cat", age:3})
    console.log(cat); // {name: "cat", age: 3, getAnimal: ƒ}
    console.log(cat.getAnimal()) // name:cat age:3
  </script>
</body>
</html>